package com.ky.manage.activity.emergency;

import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ky.manage.R;
import com.ky.manage.adapter.EmergencyInfoAdapter;
import com.ky.manage.base.BaseActivity;
import com.ky.manage.constant.OverallData;
import com.ky.manage.model.response.EmergencyInfoListResp;
import com.ky.manage.ui.RecycleViewDivider;
import com.ky.manage.utils.ScreenUtils;
import com.ky.manage.utils.ToastUtils;
import com.ky.manage.utils.ZyUtils;
import com.ky.manage.utils.http.AsyncHttpUtils;
import com.ky.manage.utils.http.BusinessHttpReqUtils;
import com.ky.manage.utils.log.ObjectUtil;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;

import java.util.ArrayList;

import cz.msebera.android.httpclient.Header;

import static com.ky.manage.constant.OverallData.Emergency_Pei_Xun;
import static com.ky.manage.constant.OverallData.Emergency_Shi_Gu_Deal;
import static com.ky.manage.constant.OverallData.Emergency_Xuan_Chuan;
import static com.ky.manage.constant.OverallData.Emergency_Yan_Lian;
import static com.ky.manage.utils.http.BusinessHttpReqUtils.SERVICE_DOMAIN;

/**
 * 应急通用页：
 * 应急培训、应急演练、宣传记录、事故处理记录页
 */
public class EmergencyListActivity extends BaseActivity {
    public int mType;
    public String mPageTitle;
    public String mServiceApi;
    private EmergencyInfoAdapter mEmergencyAdapter;
    private int mCurPageIndex = OverallData.DEFAULT_REQ_PAGE_NUM;
    private int mCurListCnt;
    private RefreshLayout refreshLayout;
    private ImageView mToTopIv;
    private RecyclerView recyclerView;
    private boolean mIsReqListData = false;

    public static void toEmergencyListActivity(BaseActivity context, int type) {
        Intent intent = new Intent(context, EmergencyListActivity.class);
        intent.putExtra("type", type);
        context.toActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_emergency_list;
    }

    @Override
    protected void initView() {
        findView(R.id.back_iv, v -> {
            finish();
        });
        findView(R.id.publish_iv, v -> {
            EmergencyPublishActivity.toEmergencyPublishActivity(EmergencyListActivity.this, mType);
        });

        mToTopIv = findView(R.id.to_top_iv, v -> {
            //置顶
            recyclerView.smoothScrollToPosition(0);
            mToTopIv.setVisibility(View.GONE);
        });
        recyclerView = findView(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mCurActivity);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.addItemDecoration(new RecycleViewDivider(mCurActivity, LinearLayoutManager.VERTICAL,
                ScreenUtils.dp2px(10), mCurActivity.getColor(R.color.gray_light)));
        mEmergencyAdapter = new EmergencyInfoAdapter(mCurActivity,
                R.layout.layout_emergency_item, new ArrayList<>());
        mEmergencyAdapter.setOnItemClickListener((adapter , view , position) -> {
            //条目点击
            EmergencyInfoListResp.EmergencyInfo emergencyInfo = mEmergencyAdapter.getItem(position);
            String id = getEmergencyId(emergencyInfo);
            if (TextUtils.isEmpty(id)) {
                return;
            }
            EmergencyDetailActivity.toEmergencyDetailActivity(this, id, mType);
        });
        recyclerView.setAdapter(mEmergencyAdapter);
        mEmergencyAdapter.notifyDataSetChanged();

        refreshLayout = findView(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(mCurActivity));
        refreshLayout.setRefreshFooter(new ClassicsFooter(mCurActivity));
        refreshLayout.setOnRefreshListener(refreshlayout -> {
            if (mIsReqListData) {
                return;
            }
            mCurPageIndex = OverallData.DEFAULT_REQ_PAGE_NUM;
            requestListData();
        });
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            if (mIsReqListData) {
                return;
            }
            mToTopIv.setVisibility(mCurPageIndex > 2 ? View.VISIBLE : View.GONE);
            requestListData();
        });
    }

    private String getEmergencyId(EmergencyInfoListResp.EmergencyInfo emergencyInfo) {
        if (null == emergencyInfo) {
            return "";
        }
        if (!TextUtils.isEmpty(emergencyInfo.publicizeId) && !"null".equals(emergencyInfo.publicizeId)) {
            return emergencyInfo.publicizeId;
        } else if (!TextUtils.isEmpty(emergencyInfo.recordId) && !"null".equals(emergencyInfo.recordId)) {
            return emergencyInfo.recordId;
        } else if (!TextUtils.isEmpty(emergencyInfo.faultId) && !"null".equals(emergencyInfo.faultId)) {
            return emergencyInfo.faultId;
        }
        return "";
    }

    @Override
    protected void initData() {
        mType = getIntent().getIntExtra("type", Emergency_Pei_Xun);
        mServiceApi = "";
        switch (mType) {
            case Emergency_Pei_Xun:
                mServiceApi = "/appApi/trainingList";
                mPageTitle = "应急培训";
                break;
            case Emergency_Shi_Gu_Deal:
                mServiceApi = "/appApi/getFaultList";
                mPageTitle = "事故处理记录";
                break;
            case Emergency_Xuan_Chuan:
                mServiceApi = "/appApi/publicizeList";
                mPageTitle = "应急宣传";
                break;
            case Emergency_Yan_Lian:
                mServiceApi = "/appApi/dirllList";
                mPageTitle = "应急演练";
                break;
            default:
                break;
        }
        findTextView(R.id.page_title_tv, mPageTitle);
        refreshLayout.autoRefresh();
//        requestListData();
    }

    private void requestListData() {
        if (!ZyUtils.getInstance().isNetConnected()) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
            return;
        }
        mIsReqListData = true;
        RequestParams httpParams = new RequestParams();
        httpParams.put("pageNum", mCurPageIndex);
        httpParams.put("pageSize", OverallData.REQ_PAGE_CNT);
        ZyUtils.getInstance().insertLog("requestListData", "req mCurPageIndex = "
                + mCurPageIndex + ", httpParams = " + ObjectUtil.objectToString(httpParams));
        AsyncHttpUtils.getInstance().get(SERVICE_DOMAIN + mServiceApi, httpParams, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                ZyUtils.getInstance().insertLog("requestListData", "onFailure statusCode = " +
                        statusCode + ", errorResponse = "+ responseString + ", throwable = " + throwable.getMessage());
                ToastUtils.showRoundRectToast("获取列表数据失败：" + throwable.getMessage());
                if (mCurPageIndex == OverallData.DEFAULT_REQ_PAGE_NUM) {
                    refreshLayout.finishRefresh();
                } else {
                    refreshLayout.finishLoadMore();
                }
                mIsReqListData = false;
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                Log.d("zhaoyan", "requestListData onSuccess rsp = " + responseString);
                EmergencyInfoListResp emergencyInfoListResp = BusinessHttpReqUtils.getInstance().parseJsonObj
                        (responseString, EmergencyInfoListResp.class);
                if (null != emergencyInfoListResp) {
                    if (emergencyInfoListResp.code == 200) {
                        int curPageDataCnt = null == emergencyInfoListResp.rows ? 0 : emergencyInfoListResp.rows.size();
                        ZyUtils.getInstance().insertLog("requestListData", "onSuccess mCurPageIndex = "
                                + mCurPageIndex + ", curPageDataCnt = " + curPageDataCnt);
                        if (mCurPageIndex == OverallData.DEFAULT_REQ_PAGE_NUM) {
                            mEmergencyAdapter.setList(curPageDataCnt == 0 ? new ArrayList<>() : emergencyInfoListResp.rows);
                            mCurListCnt = curPageDataCnt;
                            if (mCurListCnt == 0 || mCurListCnt >= emergencyInfoListResp.total) {
                                refreshLayout.finishRefreshWithNoMoreData();
                                if (mCurListCnt == 0 ) {
                                    showEmptyView();
                                }
                            } else {
                                refreshLayout.finishRefresh();
                                ++mCurPageIndex;
                            }
                        } else {
                            if (curPageDataCnt > 0 ) {
                                mEmergencyAdapter.addData(emergencyInfoListResp.rows);
                            }
                            mCurListCnt += curPageDataCnt;
                            if (curPageDataCnt == 0 || mCurListCnt >= emergencyInfoListResp.total) {
                                refreshLayout.finishLoadMoreWithNoMoreData();
                                ZyUtils.getInstance().insertLog("requestListData","没有更多数据");
                            } else {
                                refreshLayout.finishLoadMore();
                                ++mCurPageIndex;
                                ZyUtils.getInstance().insertLog("requestListData","有更多数据");
                            }
                        }
                    } else if (emergencyInfoListResp.code == 401){
                        //登陆失效，需重新登陆
                        BusinessHttpReqUtils.getInstance().autoPwdLogin(mCurActivity);
                    } else {
                        ToastUtils.showRoundRectToast("获取列表数据失败: " + emergencyInfoListResp.msg);
                    }
                } else {
                    ToastUtils.showRoundRectToast("获取列表数据失败");
                }
                mIsReqListData = false;
            }
        });
    }

    /**
     * 无数据界面
     */
    private void showEmptyView() {
        mEmergencyAdapter.getData().clear();
        mEmergencyAdapter.setEmptyView(R.layout.layout_empty_data);
        mEmergencyAdapter.notifyDataSetChanged();
    }
}